<template>
    <div class="model-management">
        <div class="table-operations">
            <a-button type="primary" @click="handleAdd">新建</a-button>
            <a-button @click="refreshList">刷新</a-button>
        </div>

        <a-table :columns="columns" :dataSource="dataSource" :pagination="pagination" :loading="loading" rowKey="id">
            <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'operation'">
                    <a-button type="link" @click="handleEdit(record)">编辑</a-button>
                    <a-popconfirm title="确定要删除吗？" @confirm="handleDelete(record)">
                        <a-button type="link" danger>删除</a-button>
                    </a-popconfirm>
                </template>
            </template>
        </a-table>

        <!-- 新增/编辑模态框 -->
        <a-modal v-model:open="modalVisible" :title="modalTitle" @ok="handleModalOk" @cancel="handleModalCancel">
            <a-form ref="formRef" :model="formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
                <a-form-item label="模型名称" name="name" :rules="[{ required: true, message: '请输入模型名称' }]">
                    <a-input v-model:value="formState.name" />
                </a-form-item>

                <a-form-item label="模型描述" name="dec" :rules="[{ required: true, message: '请输入模型描述' }]">
                    <a-input v-model:value="formState.dec" />
                </a-form-item>

                <a-form-item label="组态模型" name="configUid">
                    <a-select v-model:value="formState.configUid" @change="changeConfigUid">
                        <a-select-option v-for="option in modelOptions" :key="option.ID" :value="option.displayUid">
                            {{ option.name }}
                        </a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item label="组态展示页面" name="PageUUID">
                    <a-select v-model:value="formState.PageUUID">
                        <a-select-option v-for="option in pageOptions" :key="option.PageId" :value="option.PageId">
                            {{ option.PageName }}
                        </a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item label="数据格式" name="DataFormat" :rules="[{ required: true, message: '请选择数据格式' }]">
                    <a-select v-model:value="formState.DataFormat">
                        <a-select-option value="LittleEndian">小端</a-select-option>
                        <a-select-option value="BigEndian">大端</a-select-option>
                    </a-select>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { cvaiApi } from '/@/api/system/cvai-api';

// 表格列定义
const columns = [
    // {
    //     title: '序号',
    //     dataIndex: 'ID',
    //     key: 'ID',
    //     width: 80,
    // },
    {
        title: '模型名称',
        dataIndex: 'name',
        key: 'name',
    },
    {
        title: '模型描述',
        dataIndex: 'dec',
        key: 'dec',
    },
    {
        title: '操作',
        key: 'operation',
    },
];

// 表格数据
const dataSource = ref([]);
const loading = ref(false);
const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
});

// 模态框状态
const modalVisible = ref(false);
const modalTitle = ref('新增模型');
const isEdit = ref(false);
const currentId = ref(null);

// 表单状态
const formState = reactive({
    name: '',
    dec: '',
    type: 15,
    DataFormat: '',
    configUid: '',
    PageUUID: '',
});

const formRef = ref();

// 获取数据列表
const fetchData = async () => {
    loading.value = true;
    try {
        cvaiApi.GetS7ModelList({ type: 15 }).then((res) => {
            if (res.code === 0) {
                dataSource.value = res.list; // 将数据模型选项存储到 modelOptions 中
                pagination.total = res.list.length;
            }
        });
    } catch (error) {
        message.error('获取数据失败');
        console.error(error);
    } finally {
        loading.value = false;
    }
};

// 刷新表格
const refreshList = () => {
    fetchData();
};

// 打开新增模态框
const handleAdd = () => {
    resetForm();
    modalTitle.value = '新增模型';
    isEdit.value = false;
    modalVisible.value = true;
};

// 打开编辑模态框
const handleEdit = (record) => {
    resetForm();
    modalTitle.value = '编辑模型';
    isEdit.value = true;
    currentId.value = record.uuid;
    changeConfigUid(record.configUid);
    // 填充表单数据
    Object.keys(formState).forEach((key) => {
        formState[key] = record[key];
    });

    modalVisible.value = true;
};

// 提交表单
const handleModalOk = async () => {
    try {
        await formRef.value.validate();

        if (isEdit.value) {
            // 编辑
            const obj = {
                uuid: currentId.value,
                data: { ...formState },
            };
            cvaiApi.EditS7Model(obj).then((res) => {
                if (res.code == 200) {
                    message.success('编辑成功');
                    refreshList();
                    modalVisible.value = false;
                } else {
                    message.error('编辑失败');
                }
            });
        } else {
            // 新增
            cvaiApi.AddS7Model(formState).then((res) => {
                if (res.code == 2002) {
                    message.success('新建成功');
                    refreshList();
                    modalVisible.value = false;
                } else {
                    message.error('新建失败');
                }
            });
        }

        modalVisible.value = false;
        refreshList();
    } catch (error) {
        console.error(error);
        if (error.errorFields) {
            message.error('请填写完整信息');
        } else {
            message.error('操作失败');
        }
    }
};

// 取消模态框
const handleModalCancel = () => {
    modalVisible.value = false;
};

// 删除数据
const handleDelete = async (record) => {
    try {
        cvaiApi.DelS7Model({ uuid: record.uuid }).then((res) => {
            if (res.code == 200) {
                message.success('删除成功');
                refreshList();
            } else {
                message.error('删除失败');
            }
        });
    } catch (error) {
        message.error('删除失败');
        console.error(error);
    }
};

// 重置表单
const resetForm = () => {
    formRef.value?.resetFields();
    Object.assign(formState, {
        name: '',
        dec: '',
        type: 15,
        DataFormat: '',
        configUid: '',
        PageUUID: '',
    });
};
//组态模型options
const modelOptions = ref([]);
const pageOptions = ref([]);
function getDisplayModelListOptions() {
    cvaiApi.getDisplayModelList().then((res) => {
        modelOptions.value = res.list;
    });
}
//联动调用接口获取List
const changeConfigUid = (value) => {
    cvaiApi.getMonitorDetail({ muid: value }).then((res) => {
        if (res.code == 0) {
            pageOptions.value = res.layer;
        }
    });
};
// 初始化加载数据
onMounted(() => {
    fetchData();
    getDisplayModelListOptions();
});
</script>

<style scoped>
.table-operations {
    margin-bottom: 16px;
}

.table-operations>button {
    margin-right: 8px;
}

.model-management {
    padding: 20px;
    background: #fff;
}
</style>